export type ActionType = "action" | "completed";

import  * as anchor from '@coral-xyz/anchor';
import {ActionGetResponse, ActionPostRequest, ACTIONS_CORS_HEADERS, createPostResponse} from '@solana/actions';
import {Connection,PublicKey, Transaction} from '@solana/web3.js';
import { Votingdapp as Voting } from '../../../../anchor/target/types/votingdapp'
import { responseCookiesToRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies';

//export type ActionGetResponse = Action<"action">;

const IDL = require("../../../../anchor/target/idl/votingdapp.json")

export const OPTIONS = GET;
export async function  GET() {
    const actionMetaData: ActionGetResponse  = {
        icon: "https://www.solar.team/Solar-Github-YouTube-225d1d99211c80748fedd8709f94991b",
        title: "choose your favorite color",
        description: "red or blue?",
        label: "vote", 
        links: {
            actions: [{
                label: "vote  Red",
                href: "/api/vote?candidate=red",

            },
            {
                label: "vote bulue",
                  href: "/api/vote?candidate=blue",

            }]
        }
    };
    

     return Response.json(actionMetaData, {headers: ACTIONS_CORS_HEADERS})
}

export async  function  POST(request: Request){
    const { searchParams} = new URL(request.url);
    const candidate = searchParams.get("candidate");

    if( !candidate || (candidate !== "red" && candidate !== "blue" )){
        return Response.json({error:"Invalid candidate"}  , {status: 400,headers:ACTIONS_CORS_HEADERS});
    }

    console.log(`vote received for : ${candidate}`);

  // return Response.json({message: `thank you for voting for ${candidate}!`}, {headers:ACTIONS_CORS_HEADERS});

  const connection = new  Connection("http://192.168.186.189:8899", "confirmed");   // confirmed 只是其中一个选项， 还是finalized, 及另一值 ， 但通常用 confirmed就够了

  const program: anchor.Program<Voting> = new anchor.Program(
    IDL,
    {connection},
  )

  const body: ActionPostRequest = await request.json();

  let voter;
  try {
    voter = new PublicKey(body.account) 
  }catch(error){
    return Response.json({error:"invalid voter account "}, {status: 400, headers: ACTIONS_CORS_HEADERS});
  }

  const instruction = await program.methods.vote(
    candidate as string, new anchor.BN(1),
  ).accounts(
     {signer: voter,}
  ).instruction();

  const latestBlockhash = await connection.getLatestBlockhash();

  const transaction = new Transaction({
    feePayer: voter,
    blockhash: latestBlockhash.blockhash,
    lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  }).add(instruction);

  const response = await createPostResponse({
    fields : {
        transaction: transaction,
    }
  });

  return Response.json(response, {headers: ACTIONS_CORS_HEADERS});

}